import 'package:flutter/material.dart';
import '../models/tag_model.dart';

/// 高级搜索对话框 - Advanced Search Dialog
/// 提供更详细的搜索选项和筛选条件
class AdvancedSearchDialog extends StatefulWidget {
  final String? initialKeyword;
  final String? initialCategory;
  final String? initialFormat;
  final List<String>? initialTags;
  final DateTimeRange? initialDateRange;
  final int? minUsageCount;
  final int? maxUsageCount;
  final bool? isFavoriteOnly;
  final List<String> availableCategories;
  final List<String> availableFormats;
  final List<TagModel> availableTags;

  const AdvancedSearchDialog({
    super.key,
    this.initialKeyword,
    this.initialCategory,
    this.initialFormat,
    this.initialTags,
    this.initialDateRange,
    this.minUsageCount,
    this.maxUsageCount,
    this.isFavoriteOnly,
    required this.availableCategories,
    required this.availableFormats,
    required this.availableTags,
  });

  @override
  State<AdvancedSearchDialog> createState() => _AdvancedSearchDialogState();
}

class _AdvancedSearchDialogState extends State<AdvancedSearchDialog> {
  late TextEditingController _keywordController;
  late TextEditingController _minUsageController;
  late TextEditingController _maxUsageController;
  
  String? _selectedCategory;
  String? _selectedFormat;
  Set<String> _selectedTags = {};
  DateTimeRange? _selectedDateRange;
  bool _isFavoriteOnly = false;
  bool _searchInContent = true;
  bool _searchInTitle = true;
  bool _searchInDescription = true;
  bool _caseSensitive = false;
  bool _wholeWords = false;

  @override
  void initState() {
    super.initState();
    
    // 初始化控制器 - Initialize controllers
    _keywordController = TextEditingController(text: widget.initialKeyword);
    _minUsageController = TextEditingController(
      text: widget.minUsageCount?.toString(),
    );
    _maxUsageController = TextEditingController(
      text: widget.maxUsageCount?.toString(),
    );
    
    // 初始化状态 - Initialize state
    _selectedCategory = widget.initialCategory;
    _selectedFormat = widget.initialFormat;
    _selectedTags = widget.initialTags?.toSet() ?? {};
    _selectedDateRange = widget.initialDateRange;
    _isFavoriteOnly = widget.isFavoriteOnly ?? false;
  }

  @override
  void dispose() {
    _keywordController.dispose();
    _minUsageController.dispose();
    _maxUsageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
      ),
      child: Container(
        width: MediaQuery.of(context).size.width * 0.9,
        constraints: const BoxConstraints(
          maxWidth: 600,
          maxHeight: 700,
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 标题栏 - Title Bar
            _buildTitleBar(),
            
            // 内容区域 - Content Area
            Expanded(
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(24),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 关键词搜索 - Keyword Search
                    _buildKeywordSection(),
                    const SizedBox(height: 24),
                    
                    // 搜索范围 - Search Scope
                    _buildSearchScopeSection(),
                    const SizedBox(height: 24),
                    
                    // 分类和格式 - Category and Format
                    _buildCategoryFormatSection(),
                    const SizedBox(height: 24),
                    
                    // 标签筛选 - Tag Filter
                    _buildTagSection(),
                    const SizedBox(height: 24),
                    
                    // 日期范围 - Date Range
                    _buildDateRangeSection(),
                    const SizedBox(height: 24),
                    
                    // 使用次数 - Usage Count
                    _buildUsageCountSection(),
                    const SizedBox(height: 24),
                    
                    // 其他选项 - Other Options
                    _buildOtherOptionsSection(),
                  ],
                ),
              ),
            ),
            
            // 操作按钮 - Action Buttons
            _buildActionButtons(),
          ],
        ),
      ),
    );
  }

  /// 构建标题栏 - Build Title Bar
  Widget _buildTitleBar() {
    return Container(
      padding: const EdgeInsets.all(24),
      decoration: BoxDecoration(
        color: Theme.of(context).primaryColor.withOpacity(0.1),
        borderRadius: const BorderRadius.only(
          topLeft: Radius.circular(16),
          topRight: Radius.circular(16),
        ),
      ),
      child: Row(
        children: [
          Icon(
            Icons.search,
            color: Theme.of(context).primaryColor,
            size: 24,
          ),
          const SizedBox(width: 12),
          Text(
            '高级搜索',
            style: Theme.of(context).textTheme.headlineSmall?.copyWith(
              fontWeight: FontWeight.w600,
              color: Theme.of(context).primaryColor,
            ),
          ),
          const Spacer(),
          IconButton(
            onPressed: () => Navigator.of(context).pop(),
            icon: const Icon(Icons.close),
            tooltip: '关闭',
          ),
        ],
      ),
    );
  }

  /// 构建关键词搜索区域 - Build Keyword Search Section
  Widget _buildKeywordSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildSectionTitle('关键词搜索', Icons.text_fields),
        const SizedBox(height: 12),
        TextField(
          controller: _keywordController,
          decoration: InputDecoration(
            hintText: '输入搜索关键词...',
            prefixIcon: const Icon(Icons.search),
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(8),
            ),
            filled: true,
            fillColor: Colors.grey[50],
          ),
        ),
        const SizedBox(height: 12),
        Row(
          children: [
            Expanded(
              child: CheckboxListTile(
                title: const Text('区分大小写'),
                value: _caseSensitive,
                onChanged: (value) {
                  setState(() {
                    _caseSensitive = value ?? false;
                  });
                },
                dense: true,
                contentPadding: EdgeInsets.zero,
              ),
            ),
            Expanded(
              child: CheckboxListTile(
                title: const Text('全词匹配'),
                value: _wholeWords,
                onChanged: (value) {
                  setState(() {
                    _wholeWords = value ?? false;
                  });
                },
                dense: true,
                contentPadding: EdgeInsets.zero,
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// 构建搜索范围区域 - Build Search Scope Section
  Widget _buildSearchScopeSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildSectionTitle('搜索范围', Icons.search),
        const SizedBox(height: 12),
        CheckboxListTile(
          title: const Text('标题'),
          subtitle: const Text('在 Prompt 标题中搜索'),
          value: _searchInTitle,
          onChanged: (value) {
            setState(() {
              _searchInTitle = value ?? false;
            });
          },
        ),
        CheckboxListTile(
          title: const Text('描述'),
          subtitle: const Text('在 Prompt 描述中搜索'),
          value: _searchInDescription,
          onChanged: (value) {
            setState(() {
              _searchInDescription = value ?? false;
            });
          },
        ),
        CheckboxListTile(
          title: const Text('内容'),
          subtitle: const Text('在 Prompt 内容中搜索'),
          value: _searchInContent,
          onChanged: (value) {
            setState(() {
              _searchInContent = value ?? false;
            });
          },
        ),
      ],
    );
  }

  /// 构建分类和格式区域 - Build Category and Format Section
  Widget _buildCategoryFormatSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildSectionTitle('分类和格式', Icons.category),
        const SizedBox(height: 12),
        Row(
          children: [
            Expanded(
              child: DropdownButtonFormField<String>(
                value: _selectedCategory,
                decoration: InputDecoration(
                  labelText: '分类',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                  filled: true,
                  fillColor: Colors.grey[50],
                ),
                items: [
                  const DropdownMenuItem<String>(
                    value: null,
                    child: Text('全部分类'),
                  ),
                  ...widget.availableCategories.map((category) {
                    return DropdownMenuItem<String>(
                      value: category,
                      child: Text(category),
                    );
                  }),
                ],
                onChanged: (value) {
                  setState(() {
                    _selectedCategory = value;
                  });
                },
              ),
            ),
            const SizedBox(width: 16),
            Expanded(
              child: DropdownButtonFormField<String>(
                value: _selectedFormat,
                decoration: InputDecoration(
                  labelText: '格式',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                  filled: true,
                  fillColor: Colors.grey[50],
                ),
                items: [
                  const DropdownMenuItem<String>(
                    value: null,
                    child: Text('全部格式'),
                  ),
                  ...widget.availableFormats.map((format) {
                    return DropdownMenuItem<String>(
                      value: format,
                      child: Text(format),
                    );
                  }),
                ],
                onChanged: (value) {
                  setState(() {
                    _selectedFormat = value;
                  });
                },
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// 构建标签区域 - Build Tag Section
  Widget _buildTagSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildSectionTitle('标签筛选', Icons.label),
        const SizedBox(height: 12),
        if (widget.availableTags.isEmpty)
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.grey[100],
              borderRadius: BorderRadius.circular(8),
            ),
            child: const Text('暂无可用标签'),
          )
        else
          Container(
            height: 120,
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey[300]!),
              borderRadius: BorderRadius.circular(8),
            ),
            child: GridView.builder(
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3,
                childAspectRatio: 3,
                crossAxisSpacing: 8,
                mainAxisSpacing: 8,
              ),
              itemCount: widget.availableTags.length,
              itemBuilder: (context, index) {
                final tag = widget.availableTags[index];
                final isSelected = _selectedTags.contains(tag.name);
                
                return FilterChip(
                  label: Text(
                    tag.name,
                    style: TextStyle(
                      fontSize: 12,
                      color: isSelected ? Colors.white : tag.getColorValue(),
                    ),
                  ),
                  selected: isSelected,
                  onSelected: (selected) {
                    setState(() {
                      if (selected) {
                        _selectedTags.add(tag.name);
                      } else {
                        _selectedTags.remove(tag.name);
                      }
                    });
                  },
                  backgroundColor: tag.getColorValue().withOpacity(0.1),
        selectedColor: tag.getColorValue(),
                );
              },
            ),
          ),
      ],
    );
  }

  /// 构建日期范围区域 - Build Date Range Section
  Widget _buildDateRangeSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildSectionTitle('创建日期', Icons.date_range),
        const SizedBox(height: 12),
        InkWell(
          onTap: _selectDateRange,
          child: Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey[300]!),
              borderRadius: BorderRadius.circular(8),
              color: Colors.grey[50],
            ),
            child: Row(
              children: [
                const Icon(Icons.calendar_today, size: 20),
                const SizedBox(width: 12),
                Expanded(
                  child: Text(
                    _selectedDateRange == null
                        ? '选择日期范围'
                        : '${_formatDate(_selectedDateRange!.start)} - ${_formatDate(_selectedDateRange!.end)}',
                    style: TextStyle(
                      color: _selectedDateRange == null
                          ? Colors.grey[600]
                          : Colors.black87,
                    ),
                  ),
                ),
                if (_selectedDateRange != null)
                  IconButton(
                    onPressed: () {
                      setState(() {
                        _selectedDateRange = null;
                      });
                    },
                    icon: const Icon(Icons.clear, size: 20),
                    tooltip: '清除日期范围',
                  ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  /// 构建使用次数区域 - Build Usage Count Section
  Widget _buildUsageCountSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildSectionTitle('使用次数', Icons.trending_up),
        const SizedBox(height: 12),
        Row(
          children: [
            Expanded(
              child: TextField(
                controller: _minUsageController,
                keyboardType: TextInputType.number,
                decoration: InputDecoration(
                  labelText: '最少使用次数',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                  filled: true,
                  fillColor: Colors.grey[50],
                ),
              ),
            ),
            const SizedBox(width: 16),
            Expanded(
              child: TextField(
                controller: _maxUsageController,
                keyboardType: TextInputType.number,
                decoration: InputDecoration(
                  labelText: '最多使用次数',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                  filled: true,
                  fillColor: Colors.grey[50],
                ),
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// 构建其他选项区域 - Build Other Options Section
  Widget _buildOtherOptionsSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildSectionTitle('其他选项', Icons.tune),
        const SizedBox(height: 12),
        CheckboxListTile(
          title: const Text('仅显示收藏'),
          subtitle: const Text('只显示已收藏的 Prompt'),
          value: _isFavoriteOnly,
          onChanged: (value) {
            setState(() {
              _isFavoriteOnly = value ?? false;
            });
          },
        ),
      ],
    );
  }

  /// 构建区域标题 - Build Section Title
  Widget _buildSectionTitle(String title, IconData icon) {
    return Row(
      children: [
        Icon(icon, size: 20, color: Theme.of(context).primaryColor),
        const SizedBox(width: 8),
        Text(
          title,
          style: Theme.of(context).textTheme.titleMedium?.copyWith(
            fontWeight: FontWeight.w600,
          ),
        ),
      ],
    );
  }

  /// 构建操作按钮 - Build Action Buttons
  Widget _buildActionButtons() {
    return Container(
      padding: const EdgeInsets.all(24),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        borderRadius: const BorderRadius.only(
          bottomLeft: Radius.circular(16),
          bottomRight: Radius.circular(16),
        ),
      ),
      child: Row(
        children: [
          Expanded(
            child: OutlinedButton(
              onPressed: _resetFilters,
              child: const Text('重置'),
            ),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: ElevatedButton(
              onPressed: _applyFilters,
              child: const Text('应用筛选'),
            ),
          ),
        ],
      ),
    );
  }

  /// 选择日期范围 - Select Date Range
  Future<void> _selectDateRange() async {
    final DateTimeRange? picked = await showDateRangePicker(
      context: context,
      firstDate: DateTime(2020),
      lastDate: DateTime.now(),
      initialDateRange: _selectedDateRange,
      builder: (context, child) {
        return Theme(
          data: Theme.of(context).copyWith(
            colorScheme: Theme.of(context).colorScheme.copyWith(
              primary: Theme.of(context).primaryColor,
            ),
          ),
          child: child!,
        );
      },
    );
    
    if (picked != null) {
      setState(() {
        _selectedDateRange = picked;
      });
    }
  }

  /// 格式化日期 - Format Date
  String _formatDate(DateTime date) {
    return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
  }

  /// 重置筛选条件 - Reset Filters
  void _resetFilters() {
    setState(() {
      _keywordController.clear();
      _minUsageController.clear();
      _maxUsageController.clear();
      _selectedCategory = null;
      _selectedFormat = null;
      _selectedTags.clear();
      _selectedDateRange = null;
      _isFavoriteOnly = false;
      _searchInContent = true;
      _searchInTitle = true;
      _searchInDescription = true;
      _caseSensitive = false;
      _wholeWords = false;
    });
  }

  /// 应用筛选条件 - Apply Filters
  void _applyFilters() {
    // 验证搜索范围 - Validate search scope
    if (!_searchInTitle && !_searchInDescription && !_searchInContent) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('请至少选择一个搜索范围'),
          backgroundColor: Colors.orange,
        ),
      );
      return;
    }

    // 验证使用次数范围 - Validate usage count range
    final minUsage = int.tryParse(_minUsageController.text);
    final maxUsage = int.tryParse(_maxUsageController.text);
    
    if (minUsage != null && maxUsage != null && minUsage > maxUsage) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('最少使用次数不能大于最多使用次数'),
          backgroundColor: Colors.orange,
        ),
      );
      return;
    }

    // 构建搜索条件 - Build search criteria
    final searchCriteria = {
      'keyword': _keywordController.text.trim(),
      'category': _selectedCategory,
      'format': _selectedFormat,
      'tags': _selectedTags.toList(),
      'dateRange': _selectedDateRange,
      'minUsageCount': minUsage,
      'maxUsageCount': maxUsage,
      'isFavoriteOnly': _isFavoriteOnly,
      'searchInTitle': _searchInTitle,
      'searchInDescription': _searchInDescription,
      'searchInContent': _searchInContent,
      'caseSensitive': _caseSensitive,
      'wholeWords': _wholeWords,
    };

    Navigator.of(context).pop(searchCriteria);
  }
}